package com.itheima.api;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.ObjectId;
import com.itheima.mongo.Movement;
import com.itheima.mongo.MovementTimeLine;
import com.itheima.utils.IdWorker;
import com.itheima.utils.TimeLineService;
import com.itheima.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

//朋友圈实现类
@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    //数据库
    private MongoTemplate mongoTemplate;

    @Autowired
    //配置主键自增类
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    //发布动态
    @Override
    public void publish(Movement movement) {
        //1. 保存动态数据
        //设置动态表主键自增 说明动态条数增加
        movement.setPid(idWorker.getNextId("movement"));
        //设置发布动态时间
        movement.setCreated(System.currentTimeMillis());
        //将数据保存到数据库
        mongoTemplate.save(movement);
        //2. 保存好友时间线数据
        timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
    }

    //查询个人动态
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //创建Criteria 条件对象 查询条件用户id 查询表名称userId
        Criteria criteria = Criteria.where("userId").is(userId);
        //创建Query对象 查询对象 调用查询方法 该用户的动态
        Query query = Query.query(criteria);
        //查询总记录数
        //调用数据库 去动态表Movement.class 统计该用户动态总数
        long count = mongoTemplate.count(query, Movement.class);
        //设置分页查询参数
        //从0也开始查询参数
        query.skip((page -1 ) * pagesize).limit(pagesize)
                //根据发布时间created 倒序排序desc
                .with(Sort.by(Sort.Order.desc("created")));
        //查询分页数据列表
        //调用数据库查找方法 根据query 条件查询 动态表Movement.class
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        //构造返回值
        //返回查询到的 页数 总页数 多少条动态  动态数据
        return new PageResult(page,pagesize,count,movements);
    }

    /**
     * 查询好友动态
     * @param page
     * @param pagesize
     * @param friendId
     */
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long friendId) {
        //1、根据friendId查询时间线表
        //创建查询对象
        Query query = Query.query(
                //Criteria条件对象 查询好友id
                Criteria.where("friendId").is(friendId))
                //从第0也查询到最后
                .skip((page -1) * pagesize).limit(pagesize)
                //通过时间降序排序
                .with(Sort.by(Sort.Order.desc("created")));
        //通过好友id条件  去MovementTimeLine.class 好友发布的动态id
        List<MovementTimeLine> lineList = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id列表
        List<ObjectId> list = CollUtil.getFieldValues(lineList, "movementId", ObjectId.class);
        //3、根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(list));
        //返还 从数据库查询到的所有好友动态
        return mongoTemplate.find(movementQuery,Movement.class);
    }

    //根据pid查询   pids 推荐动态数据
    public List<Movement> findMovementsByPids(List<Long> pids) {
        //查询多少条动态数据 返回给前端
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query,Movement.class);
    }

    //随机查询多条数据
    public List<Movement> randomMovements(Integer counts) {
        //1、创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(counts));
        //2、调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3、获取统计结果
        return results.getMappedResults();
    }

    //通过id查询动态
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }

    //根据用户ID分页查询用户发布的动态列表方法
    @Override
    public PageResult findByUserIdd(Long uid, Integer state, Integer page, Integer pagesize) {
        Query query = new Query();
        if(uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        //查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //设置分页参数
        query.with(Sort.by(Sort.Order.desc("created"))).limit(pagesize).skip((page -1) * pagesize);

        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }

}
